package com.chendx.store.page.service.impl;

import com.alibaba.fastjson.JSON;
import com.chendx.model.goods.pojo.Sku;
import com.chendx.model.goods.pojo.Spu;
import com.chendx.model.goods.vo.SkuVo;
import com.chendx.model.goods.vo.SpuVo;
import com.chendx.store.page.feign.GoodsFeign;
import com.chendx.store.page.service.PageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chendx on 2022/4/18.
 */
@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${html.page}")
    private String htmlPagePath;

    @Override
    public Map<String, Object> buildDataModel(Long spuId) {
        Map<String, Object> dataMap = new HashMap<>();
        Spu spu = goodsFeign.findById(spuId);

        SpuVo spuVo = new SpuVo();
        BeanUtils.copyProperties(spu,spuVo);
        spuVo.setId(spu.getId()+"");

        List<Sku> skuList = goodsFeign.findBySpuId(Long.valueOf(spuVo.getId()));
        List<SkuVo> skuVos = new ArrayList<>();
        if(spu.getImages()!=null) {
            dataMap.put("imageList", spu.getImages().split(","));
        }
        dataMap.put("spu",spuVo);
        dataMap.put("specificationList", JSON.parseObject(spu.getSpecItems(),Map.class));
        Map<String,Object> mapp = new HashMap<>();
        for (Sku sku : skuList){
            SkuVo skuVo = new SkuVo();
            BeanUtils.copyProperties(sku,skuVo);
            skuVo.setId(sku.getId()+"");

            skuVo.setSpuId(spu.getId()+"");
            Map<String,Object> map = JSON.parseObject(spu.getSpecItems(), Map.class);

           /* for (String key : map.keySet()){
                if (sku.getCategoryName().equals("手机") && !key.equals("运行内存") && !key.equals("机身内存")){
                    mapp.put(key,map.get(key));
                }else if (sku.getCategoryName().equals("电视") && !key.equals("屏幕尺寸") && !key.equals("电视类型")){
                    mapp.put(key,map.get(key));
                } else if (!key.endsWith("false")){
                    mapp.put(key,map.get(key));
                }else {
                    mapp.put(key,map.get(key));
                }
            }*/
            sku.setSpec(JSON.toJSONString(mapp));
            skuVo.setSpec(sku.getSpec());
            skuVos.add(skuVo);
        }
        dataMap.put("skuList",skuVos);
        return dataMap;
    }


    public Map<String, Object> buildSpuSkuDataModel(SpuVo spu,List<Sku> skuList,Long skuId) {
        Map<String, Object> dataMap = new HashMap<>();
        // Spu spu = spuFeign.findById(String.valueOf(spuId)).getData();
        Sku oneSku = goodsFeign.findSkuById(skuId);
        if(spu.getImages()!=null) {
            dataMap.put("skuImages", spu.getImages().split(","));
        }
        dataMap.put("specificationList", JSON.parseObject(spu.getSpecItems(),Map.class));
        List<SkuVo> skuVos = new ArrayList<>();
        Map<String,Object> mapp = new HashMap<>();
        for (Sku sku : skuList){
            SkuVo skuVo = new SkuVo();
            BeanUtils.copyProperties(sku,skuVo);
            skuVo.setId(String.valueOf(sku.getId()));
            skuVo.setSpuId(spu.getId());
            Map<String,Object> map = JSON.parseObject(sku.getSpec(), Map.class);

            String specItems = spu.getSpecItems();
            Map<String,Object> spumap = JSON.parseObject(specItems, Map.class);

            for (String key : map.keySet()){

                spumap.keySet().stream().filter(spuKey -> spuKey.equals(key)).forEach(spuKey -> {
                    mapp.put(key, map.get(key));
                    if (sku.getId().equals(oneSku.getId())) {
                        dataMap.put("sku", skuVo);
                        if (sku.getImages() != null) {
                            dataMap.put("skuImages", sku.getImages().split(","));
                        }
                    }
                });
               /* if (!key.equals("运行内存") && !key.equals("机身内存")){
                    mapp.put(key,map.get(key));
                    if (sku.getId().equals(oneSku.getId())){
                        dataMap.put("sku",skuVo);
                        if(sku.getImages()!=null) {
                            dataMap.put("skuImages", sku.getImages().split(","));
                        }
                    }
                }
                if (!key.equals("屏幕尺寸") && !key.equals("屏幕类型")){
                    mapp.put(key,map.get(key));
                    if (sku.getId().equals(oneSku.getId())){
                        dataMap.put("sku",skuVo);
                        if(sku.getImages()!=null) {
                            dataMap.put("skuImages", sku.getImages().split(","));
                        }
                    }
                }*/
            }
            sku.setSpec(JSON.toJSONString(mapp));
            skuVo.setSpec(sku.getSpec());
            skuVos.add(skuVo);
        }
        dataMap.put("spu",spu);
        dataMap.put("skuList",skuVos);
        return dataMap;
    }

    @Override
    public void createPageHtml(Long spuId) {
        String path = htmlPagePath+"spu";
        Context context = new Context();
        Map<String, Object> dataMap = buildDataModel(spuId);
        context.setVariables(dataMap);

        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        File dest = new File(dir,spuId +".html");
        // 3.生成页面
        try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
            //模板的文件
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void createSkuPageHtml(Long spuId, Long skuId) {
        String path = htmlPagePath+spuId;
        Spu spu = goodsFeign.findById(spuId);

        SpuVo spuVo = new SpuVo();
        BeanUtils.copyProperties(spu,spuVo);
        spuVo.setId(spu.getId()+"");

        //根据spuId查询Sku集合
        List<Sku> skuList = goodsFeign.findBySpuId(spu.getId());
        Map<String, Object> dataMap = new HashMap<>();
        Context context = new Context();
        for (Sku sku : skuList){
            if (StringUtils.isEmpty(skuId)){
                dataMap = buildSpuSkuDataModel(spuVo,skuList,Long.valueOf(sku.getId()));
                context.setVariables(dataMap);
                File dir = new File(path);
                if (!dir.exists()){
                    dir.mkdirs();
                }
                File dest = new File(dir,sku.getId() +".html");
                // 3.生成页面
                try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
                    //模板的文件
                    templateEngine.process("skuitem", context, writer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (skuId.equals(sku.getId())){
                dataMap = buildSpuSkuDataModel(spuVo,skuList,Long.valueOf(skuId));
                context.setVariables(dataMap);
                File dir = new File(path);
                if (!dir.exists()){
                    dir.mkdirs();
                }
                File dest = new File(dir,skuId +".html");
                // 3.生成页面
                try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
                    //模板的文件
                    templateEngine.process("skuitem", context, writer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
